<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-05-10
 * Time: 10:08
 */

namespace Think;


class WeChatApi {

     //构造函数，获取Access Token
    public function __construct($app_id = NULL, $app_secret = NULL)
     {
         $wxConfig=new \WxPayConfig();
        if($app_id){
             $this->appid = $wxConfig::APPID;
         }
        if($app_secret){
            $this->appsecret = $wxConfig::APPSECRET;
         }

         //hardcode
         $this->lasttime = 1395049256;
        $this->access_token = "nRZvVpDU7LxcSi7GnG2LrUcmKbAECzRf0NyDBwKlng4nMPf88d34pkzdNcvhqm4clidLGAS18cN1RTSK60p49zIZY4aO13sF-eqsCs0xjlbad-lKVskk8T7gALQ5dIrgXbQQ_TAesSasjJ210vIqTQ";
         if (time() > ($this->lasttime + 7200)){
             $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
             $result = json_decode($res, true);

             $this->access_token = $result["access_token"];
             $this->lasttime = time();
         }
     }

     //获取关注者列表
     public function get_user_list($next_openid = NULL)
     {

         $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
         $res = $this->https_request($url);
         return json_decode($res, true);
     }

     //获取用户基本信息
     public function get_user_info($openid)
    {
         $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
         $res = $this->https_request($url);
         return json_decode($res, true);
     }

    //批量获取用户基本信息
    public function batch_get_fans_info($data){
        $url="https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=".$this->access_token;
        $res=$this->https_request($url,json_encode($data));
        return json_decode($res,true);
    }

    //获取标签
    public function get_tag_list(){
        $url="https://api.weixin.qq.com/cgi-bin/tags/get?access_token=".$this->access_token;
        $res=$this->https_request($url);
        return json_decode($res,true);
    }

     //创建菜单
     public function create_menu($data)
     {
         $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
         $res = $this->https_request($url, $data);
         return json_decode($res, true);
     }

    /************************************
     * 获取菜单
     ************************************/
     public function get_menu(){
         $url='https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$this->access_token;
         return $this->https_request($url);
     }

    /************************************
     * 删除菜单
     ************************************/
    public function delete_menu(){
        $url='https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->access_token;
        return $this->https_request($url);
    }

     //发送客服消息，已实现发送文本，其他类型可扩展
     public function send_custom_message($touser, $type, $data)
     {
        $msg = array('touser' =>$touser);
         switch($type)
         {
             case 'text':
                 $msg['msgtype'] = 'text';
                 $msg['text']    = array('content'=> urlencode($data));
                 break;
         }
         $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
         return $this->https_request($url, urldecode(json_encode($msg)));
     }

     //发送模板消息
     public function send_template_message($data){

         $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
         return $this->https_request($url,(json_encode($data)));
     }

     //生成参数二维码
     public function create_qr_code($scene_type, $scene_id)
     {
        switch($scene_type)
    {
             case 'QR_LIMIT_SCENE': //永久
                 $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                 break;
             case 'QR_SCENE':       //临时
                 $data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                 break;
         }

         $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
         $res = $this->https_request($url, $data);
         $result = json_decode($res, true);

         return $result;
     }

     //创建分组
     public function create_group($name)
     {
         $data = '{"group": {"name": "'.$name.'"}}';
         $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
         $res = $this->https_request($url, $data);
         return json_decode($res, true);
     }

     //移动用户分组
     public function update_group($openid, $to_groupid)
     {
         $data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
         $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
         $res = $this->https_request($url, $data);
         return json_decode($res, true);
     }

     //上传多媒体文件
     public function upload_media($type, $file)
     {
         $data = array("media"  => "@".dirname(__FILE__).'\\'.$file);
         $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
         $res = $this->https_request($url, $data);
         return json_decode($res, true);
     }
      //下载多媒体文件
    public function update_media($media_id){

        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&media_id=".$media_id;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
     //https请求（支持GET和POST）
     protected function https_request($url, $data = null)
     {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
         if (!empty($data)){
             curl_setopt($curl, CURLOPT_POST, 1);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         }
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         $output = curl_exec($curl);
         curl_close($curl);
         return $output;
     }

    /*
     *@todo api微信网页授权
     * */
    //通过code换取网页授权access_token
    public function get_login_access_token($redirect_uri,$scope,$state){
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->app_id.'&redirect_uri='.$redirect_uri.
            '&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
       $this->wxHeader($url);
    }

    public function get_user_openid($code){
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->app_id.'&secret='.$this->app_secret.
            '&code='.$code.'&grant_type=authorization_code ';
        $res=$this->https_request($url);
        return $res;
    }

    /****************************************************
     *        微信OAUTH跳转指定URL
     ****************************************************/
    public function wxHeader($url){
        header("location:".$url);
    }

    /*******************************************************
     *      微信卡券：创建卡券
     *******************************************************/
    public function card_created($jsonData) {

        $url            = "https://api.weixin.qq.com/card/create?access_token=" . $this->access_token;
        $result         = $this->https_request($url,$jsonData);
        $jsoninfo       = json_decode($result, true);
        return $jsoninfo;
    }

    public function oauth2_authorize($redirect_url, $scope, $state = NULL)
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$redirect_url."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
        return $url;
    }

    //生成OAuth2的Access Token
    public function oauth2_access_token($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //生成随机字符串
    function create_noncestr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++ ){
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    //生成签名
    function get_biz_sign($bizObj)
    {
        //参数小写
        foreach ($bizObj as $k => $v){
            $bizParameters[strtolower($k)] = $v;
        }
        //字典序排序
        ksort($bizParameters);
        //URL键值对拼成字符串
        $buff = "";
        foreach ($bizParameters as $k => $v){
            $buff .= $k."=".$v."&";
        }
        //去掉最后一个多余的&
        $buff2 = substr($buff, 0, strlen($buff) - 1);
        //sha1签名
        return sha1($buff2);
    }

    //微信接受文本消息处理
    public function receiveText($postObj,$data=null){
        $keyword= trim($postObj->Content);
        $contentStr='';
        foreach( $data as $key=>$value){
            if(in_array($keyword,explode(',',$value['title']))){
                $contentStr=$value['content'];
            }
        }
        if(empty($contentStr)){
            $contentStr='亲,我的客服人员,将会与您联系！';
        }
        $res=$this->send_temple($postObj,$contentStr);
        return $res;

    }

    //微信接受图片消息处理
    public function receiveImage($postObj){
        return true;
    }

    //微信接受位置消息处理
    public function receiveLocation($postObj){
        return true;
    }

    //微信接受语音消息处理
    public function receiveVoice($postObj){
        return true;
    }

    //微信接受视频消息处理
    public function receiveVideo($postObj){
        return true;
    }

    //微信接受链接消息处理
    public function receiveLink($postObj){
        return true;
    }

    //接收事件，关注等
    public function receiveEvent($postObj,$data=null){
        $contentStr = "";
        switch ($postObj->Event)
        {
            case "subscribe":
                $content = "感谢您的关注,祝您生活愉快";    //关注后回复内容
                $contentStr=$this->send_temple($postObj,$content);
                if (isset($postObj->EventKey)){

                    //这是扫描带参数二维码,把用户信息保存
                    $info_code=M('wechat_code_info')->where(array('ticket'=>(string)$postObj->Ticket))->find();
                    $content = $info_code['content'];    //关注后回复内容
                    $data['scene_id']=$info_code['id'];
                    $data['time']=time();
                    $data['open_id']=(string)$postObj->FromUserName;
                    M("wechat_code_user")->add($data);
                    //这是扫描带参数二维码,把用户信息保存

                    $contentStr=$this->send_temple($postObj,$content);
                }
                break;
            case "unsubscribe":
                $contentStr = "";
                break;
            case "CLICK":
                $contentStr =  $this->receiveClick($postObj,$data);    //点击事件
                break;
            case "SCAN":
                //这是扫描带参数二维码,把用户信息保存
                $info_code=M('wechat_code_info')->where(array('id'=>$postObj->EventKey))->find();
                $content = $info_code['content'];    //关注后回复内容
                $data['scene_id']=(int)$postObj->EventKey;
                $data['time']=time();
                $data['open_id']=(string)$postObj->FromUserName;
                M("wechat_code_user")->add($data);
                //这是扫描带参数二维码,把用户信息保存

                $contentStr=$this->send_temple($postObj,$content);
                break;
            default:
                $contentStr = "receive a new event: ".$postObj->Event;
                break;
        }

        return $contentStr;
    }



    //点击事件
    public function receiveClick($postObj,$data){
        foreach($data as $key=>$value){
            if($postObj->EventKey==$value['key_name']){
                $content=$value['reply'];
            }
        }
        $res=$this->send_temple($postObj,$content);
       return $res;
    }

    //事件内容
    public function send_temple($postObj,$content){
        $fromUsername = $postObj->FromUserName;//发送消息方ID
        $toUsername = $postObj->ToUserName;//接收消息方ID
        $times = time();//发送时间
        $msgType = "text";
        $textTpl = "<xml>
       <ToUserName><![CDATA[%s]]></ToUserName>
       <FromUserName><![CDATA[%s]]></FromUserName>
       <CreateTime>%s</CreateTime>
       <MsgType><![CDATA[%s]]></MsgType>
       <Content><![CDATA[%s]]></Content>
       </xml>";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $times, $msgType,$content);
        return $resultStr;
    }



}